import React, {Component} from "react";
import {Button, Col, DatePicker, Form, Input, Row, Select, message, InputNumber, Collapse} from "antd";
import moment from 'moment';

import {getCrmRecordFromSql, getOptions, isBlank} from "../util/util";
import dayjs from 'dayjs';
import '../styles.css';

const dateFormat = 'YYYY-MM-DD';

const ZOHO = window.ZOHO;
const {TextArea} = Input;

class QuoteForm extends Component {
    formRef = React.createRef();

    constructor(props) {
        super(props);
        this.state = {
            // 客户
            accountOptions: [],
            // 联系人
            contactOptions: [],
            // 抬头
            shipperInformationOptions: [],
            // 币种
            CurrencyOptions: [],
            // 目的港
            DestinationPortOptions: [],
            // 起运港
            LoadingPortOptions: [],
            // 商机
            DealsOptions: [],
            items: [
                {
                    key: '1',
                    label: '对外报价信息',
                    children: "",
                    showArrow: false,
                },
                {
                    key: '2',
                    label: '客户信息',
                    children: <p>{345}</p>,
                    showArrow: false,
                },
                {
                    key: '3',
                    label: '装运信息',
                    children: <p>{345}</p>,
                    showArrow: false,
                },
                {
                    key: '4',
                    label: '汇率信息',
                    children: <p>{345}</p>,
                    showArrow: false,
                },
                {
                    key: '5',
                    label: '条款',
                    children: <p>{345}</p>,
                    showArrow: false,
                },
            ],
            paddedNumber: 0,
        };
    }

    async componentDidMount() {
        const {current} = this.formRef;
        let shipperOptions = [];
        let accountOptions = [];
        let contactOptions = [];
        let CurrencyOptions = [];
        // 目的港
        let DestinationPortOptions = [];
        // 起运港
        let LoadingPortOptions = [];
        // 商机
        let DealsOptions = [];
        try {
            let ShipperInformations = await getOptions("ShipperInformation");
            shipperOptions = ShipperInformations.map(item => ({
                value: item.id,
                label: item.Name,
            }));
            let accounts = await getOptions("Accounts");
            accountOptions = accounts.map(item => ({
                value: item.id,
                label: item.Account_Name,
            }));
            let Currencytypes = await getOptions("Currencytype");
            CurrencyOptions = Currencytypes.map(item => ({
                value: item.id,
                label: item.Name,
            }));
            let PortInformations = await getOptions("PortInformation", "id,Name,PortType");
            PortInformations.map(item => {
                if (item.PortType === "目的港") {
                    DestinationPortOptions.push({
                        value: item.id,
                        label: item.Name,
                    })
                }
                if (item.PortType === "装运港") {
                    LoadingPortOptions.push({
                        value: item.id,
                        label: item.Name,
                    })
                }

            });

            let Deals = await getOptions("Deals", "id,Deal_Name");
            DealsOptions = Deals.map(item => ({
                value: item.id,
                label: item.Deal_Name,
            }));
        } catch (error) {
            console.error(error);
        }
        current.setFieldValue('Paymentterms', 'Please note:\n' +
            '    1.The quotation is based on above mentioned packaging way. \n' +
            '    2.Printed stand-up bag is recommended, and relative occuring plate charge is at buyer＇s account. The plate cost depends on bag size and exact design,which should be offered by seller upon receipt of artwork.');
        current.setFieldValue('Dateofinvoice', dayjs(moment().format(dateFormat), 'YYYY-MM-DD'));
        if (window.id !== undefined) {
            try {
                const data = await ZOHO.CRM.API.getRecord({
                    Entity: "Quotations",
                    approved: "both",
                    RecordID: window.id,
                });
                const formdata = data.data[0];
                let accountid = formdata.Account?.id;
                console.log(formdata);
                formdata.Dateofinvoice = isBlank(formdata.Dateofinvoice) ? undefined : moment(formdata.Dateofinvoice);
                formdata.Quotationvalidityperiod = isBlank(formdata.Quotationvalidityperiod) ? undefined : moment(formdata.Quotationvalidityperiod);
                formdata.Companyletterhead = {
                    value: formdata.Companyletterhead?.id,
                    label: formdata.Companyletterhead?.name,
                };
                formdata.Account = {
                    value: formdata.Account?.id,
                    label: formdata.Account?.name,
                }
                formdata.Accountcontactperson = {
                    value: formdata.Accountcontactperson?.id,
                    label: formdata.Accountcontactperson?.name,
                }
                formdata.Currencys = {
                    value: formdata.Currencys?.id,
                    label: formdata.Currencys?.name,
                };
                formdata.DestinationPort = {
                    value: formdata.DestinationPort?.id,
                    label: formdata.DestinationPort?.name,
                }
                formdata.LoadingPort = {
                    value: formdata.LoadingPort?.id,
                    label: formdata.LoadingPort?.name,
                }
                formdata.Deals = {
                    value: formdata.Deals?.id,
                    label: formdata.Deals?.name,
                }
                current.setFieldsValue(formdata);
                if (accountid !== undefined) {
                    let options = await this.getContactOptions(accountid);
                    console.log(options)
                    contactOptions = options?.map(item => ({
                        value: item.id,
                        label: item.Full_Name,
                    }));
                }
            } catch (error) {
                console.error(error);
            }
        }
        // 有商机自动带出
        if (!isBlank(window.dealsid)) {
            this.changeDeals({key: window.dealsid})
        }
        this.setState({ // 客户
            accountOptions: accountOptions,
            contactOptions: contactOptions,
            shipperInformationOptions: shipperOptions,
            CurrencyOptions: CurrencyOptions,
            DestinationPortOptions: DestinationPortOptions,
            LoadingPortOptions: LoadingPortOptions,
            DealsOptions: DealsOptions,
        });
    }


    getContactOptions = async (accountid) => {
        return await getCrmRecordFromSql(`select id,Full_Name from Contacts where  Account_Name =${accountid}`);
    }

    changeDeals = async (value) => {
        const {current} = this.formRef;
        if (isBlank(value)) {
            await this.changeAccount(null)
            return
        }
        ZOHO.CRM.API.getRecord({
            Entity: "Deals", approved: "both", RecordID: value.key
        }).then(data => {
            let deal = data.data[0];
            current.setFieldValue("Deals", {
                value: value.key,
                label: deal.Deal_Name
            })
            this.changeAccount({key: deal.Account_Name.id, label: deal.Account_Name.name})
        })
    }

    changeAccount = async (value) => {
        const {current} = this.formRef;
        console.log(value)
        if (isBlank(value)) {
            current.setFieldValue("Account", {
                value: null,
                label: null,
            })
            current.setFieldValue("Accountcontactperson", {
                value: null,
                label: null
            })
            current.setFieldValue("AccountCode", null)
            current.setFieldValue("Companyletterhead", {
                value: null,
                label: null
            })
            current.setFieldValue("Shipper", null)
            this.changeCurrency(undefined)
            current.setFieldValue("DestinationPort", {
                value: null,
                label: null
            })
            current.setFieldValue("LoadingPort", {
                value: null,
                label: null
            })
            current.setFieldValue("Termsandconditions", null)
            return
        }
        current.setFieldValue("Account", {
            value: value.key,
            label: value.label
        })
        current.setFieldValue("Accountcontactperson", {
            value: null,
            label: null
        })
        ZOHO.CRM.API.getRecord({
            Entity: "Accounts", approved: "both", RecordID: value.key
        }).then(data => {
            current.setFieldValue("AccountCode", data.data[0].CustomerCode)
            current.setFieldValue("Companyletterhead", {
                value: data.data[0].CompanyHead?.id,
                label: data.data[0].CompanyHead?.name
            })
            current.setFieldValue("Shipper", data.data[0].field)
            this.changeCurrency({
                key: data.data[0].Currencys?.id,
                label: data.data[0].Currencys?.name
            })
            current.setFieldValue("DestinationPort", {
                value: data.data[0].DestinationPort?.id,
                label: data.data[0].DestinationPort?.name
            })
            current.setFieldValue("LoadingPort", {
                value: data.data[0].LoadingPort?.id,
                label: data.data[0].LoadingPort?.name
            })
            current.setFieldValue("Termsandconditions", data.data[0].PaymentMethod)

        })
        let options = await this.getContactOptions(value.key);
        console.log(options)
        let contactOptions = options?.map(item => ({
            value: item?.id,
            label: item?.Full_Name,
        }));
        this.setState({ // 客户
            contactOptions: contactOptions,
        });
    }
    changeContact = (value) => {
        const {current} = this.formRef;
        if (isBlank(value)) {
            current.setFieldValue("Accountcontactperson", {
                value: null,
                label: null
            })
            return
        }
        current.setFieldValue("Accountcontactperson", {
            value: value.key,
            label: value.label
        })
    }
    changeCompanyletterhead = (value) => {
        const {current} = this.formRef;
        let {paddedNumber} = this.state;

        if (isBlank(value)) {
            current.setFieldValue("Companyletterhead", {
                value: null,
                label: null
            })
            return
        }
        current.setFieldValue("Companyletterhead", {
            value: value.key,
            label: value.label
        })
        ZOHO.CRM.API.getRecord({
            Entity: "ShipperInformation", approved: "both", RecordID: value.key
        }).then(async data => {
            current.setFieldValue("Shipper", data.data[0].China_Name)
            if (isBlank(window.id)) {
                let func_name = "serialnumber";
                let req_data = {
                    "arguments": JSON.stringify({
                        "id": "185647000001230419",
                        "count": 1
                    })
                };
                if (paddedNumber === 0) {
                    await ZOHO.CRM.FUNCTIONS.execute(func_name, req_data)
                        .then(function (data) {
                            paddedNumber = data.details.output.toString().padStart(4, '0');
                        })
                    this.setState({paddedNumber: paddedNumber}, () => {
                        // 在回调函数中执行其他操作
                    });
                }
                let code = `BJ${value.label}${moment().format('YYYYMM')}${paddedNumber}`;
                console.log(code)
                current.setFieldValue("Name", code)
            }
        })
    }
    changeCurrency = (value) => {
        const {current} = this.formRef;

        if (isBlank(value)) {
            current.setFieldValue("Currencys", {
                value: '',
                label: ''
            })
            current.setFieldValue("Exchangerate", 1)
        } else {
            current.setFieldValue("Currencys", {
                value: value.key,
                label: value.label
            })
            ZOHO.CRM.API.getRecord({
                Entity: "Currencytype", approved: "both", RecordID: value.key
            }).then(data => {
                current.setFieldValue("Exchangerate", data.data[0].Exchangerates)
            })
        }
    }
    changePort = (fieldname, value) => {
        const {current} = this.formRef;

        if (isBlank(value)) {
            current.setFieldValue(fieldname, {
                value: null,
                label: null
            })
            return;
        }
        current.setFieldValue(fieldname, {
            value: value.key,
            label: value.label
        })

    }
    handleCancel = () => {
        const {current} = this.formRef;
        current.resetFields();
    };

    scrollToTop = () => {
        window.scrollTo({
            top: 0,
            behavior: "smooth"  // 使用平滑滚动效果
        });
    }


    render() {
        const {
            accountOptions,
            contactOptions,
            shipperInformationOptions,
            CurrencyOptions,
            LoadingPortOptions,
            DestinationPortOptions,
            DealsOptions,
            items,
        } = this.state;
        const {Item} = Form;

        return (
            <div>

                <Form ref={this.formRef}>
                    <Collapse size="middle" defaultActiveKey={[1, 2, 3, 4, 5]}>
                        <Collapse.Panel key="1" header="对外报价信息" showArrow={false}>
                            <Row gutter={16} align="middle">
                                <Col span={12}>
                                    <Item label="报价项目名称" name="Quotationitemname" labelAlign="right">
                                        <Input className="input-field"/>
                                    </Item>
                                </Col>
                                <Col span={12}>
                                    <Item label="报价日期" name="Dateofinvoice" labelAlign="right">
                                        <DatePicker className="input-field"
                                                    defaultValue={dayjs(moment().format(dateFormat), 'YYYY-MM-DD')}
                                                    format={dateFormat}/>
                                    </Item>
                                </Col>
                            </Row>
                            <Row gutter={16} align="middle">
                                <Col span={12}>
                                    <Item label="报价有效期" name="Quotationvalidityperiod" labelAlign="right">
                                        <DatePicker className="input-field" format={dateFormat}/>
                                    </Item>
                                </Col>
                                <Col span={12}>
                                    <Item label="报价方式" name="Quotationmethod">
                                        <Select allowClear className="input-field">
                                            <Select.Option value="包装袋报价">包装袋报价</Select.Option>
                                            <Select.Option value="公斤报价">公斤报价</Select.Option>
                                            <Select.Option value="整箱报价">整箱报价</Select.Option>
                                        </Select>
                                    </Item>
                                </Col>
                            </Row>
                        </Collapse.Panel>
                        <Collapse.Panel key="2" header="客户信息" showArrow={false}>
                            <Row gutter={16} align="middle">
                                <Col span={12}>
                                    <Item label="商机" name="Deals" labelAlign="right">
                                        <Select
                                            allowClear
                                            className="input-field"
                                            labelInValue
                                            showSearch
                                            onChange={this.changeDeals}
                                            options={DealsOptions}
                                            optionLabelProp="label"
                                            filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                        />
                                    </Item>
                                </Col>
                                <Col span={12}>
                                    <Item label="客户" name="Account" labelAlign="right"
                                          rules={[{required: true, message: '请选择客户'}]}>
                                        <Select
                                            allowClear
                                            className="input-field"
                                            labelInValue
                                            showSearch
                                            onChange={this.changeAccount}
                                            options={accountOptions}
                                            optionLabelProp="label"
                                            filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                        />
                                    </Item>
                                </Col>

                            </Row>
                            <Row gutter={16} align="middle">
                                <Col span={12}>
                                    <Item label="客户代码" name="AccountCode" labelAlign="right">
                                        <Input className="input-field" disabled={true}/>

                                    </Item>
                                </Col>

                                <Col span={12}>
                                    <Item label="客户联系人" name="Accountcontactperson">
                                        <Select
                                            className="input-field"
                                            labelInValue
                                            showSearch
                                            allowClear
                                            onChange={this.changeContact}
                                            options={contactOptions}
                                            optionLabelProp="label"
                                            filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                        />
                                    </Item>
                                </Col>
                            </Row>
                        </Collapse.Panel>
                        <Collapse.Panel key="3" header="装运信息" showArrow={false}>
                            <Row gutter={16}>
                                <Col span={12}>
                                    <Item label="装运港" name="LoadingPort">
                                        <Select
                                            allowClear
                                            className="input-field"
                                            labelInValue
                                            showSearch
                                            onChange={value => {
                                                this.changePort('LoadingPort', value)
                                            }}
                                            options={LoadingPortOptions}
                                            optionLabelProp="label"
                                            filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                        />
                                    </Item>
                                </Col>
                                <Col span={12}>
                                    <Item label="目的港" name="DestinationPort">
                                        <Select
                                            allowClear
                                            className="input-field"
                                            labelInValue
                                            showSearch
                                            onChange={value => {
                                                this.changePort('DestinationPort', value)
                                            }}
                                            options={DestinationPortOptions}
                                            optionLabelProp="label"
                                            filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                        />
                                    </Item>
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col span={12}>
                                    <Item label="发货人代码" name="Companyletterhead"
                                          rules={[{required: true, message: '请选择发货人代码'}]}>
                                        <Select
                                            allowClear
                                            className="input-field"
                                            labelInValue
                                            showSearch
                                            onChange={this.changeCompanyletterhead}
                                            options={shipperInformationOptions}
                                            optionLabelProp="label"
                                            filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                        />
                                    </Item>
                                </Col>
                                <Col span={12}>
                                    <Item label="发货人名称" name="Shipper">
                                        <Input className="input-field" disabled={true}/>
                                    </Item>
                                </Col>
                            </Row>
                        </Collapse.Panel>
                        <Collapse.Panel key="4" header="汇率信息" showArrow={false}>
                            <Row gutter={16}>
                                <Col span={12}>
                                    <Item label="币种" name="Currencys">
                                        <Select
                                            className="input-field"
                                            allowClear
                                            labelInValue
                                            showSearch
                                            onChange={this.changeCurrency}
                                            options={CurrencyOptions}
                                            optionLabelProp="label"
                                            filterOption={(input, option) => (option?.label ?? '').includes(input)}
                                        />
                                    </Item>
                                </Col>
                                <Col span={12}>
                                    <Item label="汇率" name="Exchangerate">
                                        <InputNumber className="input-field" step={0.01}/>
                                    </Item>
                                    <Item label="" name="Name" hidden={true}>
                                        <Input className="input-field"/>
                                    </Item>
                                </Col>
                            </Row>
                        </Collapse.Panel>
                        <Collapse.Panel key="5" header="条款信息" showArrow={false}>
                            <Row gutter={16}>
                                <Col span={16}>
                                    <Item label="条款" name="Termsandconditions">
                                        <TextArea className="input-field" rows={4}/>
                                    </Item>
                                </Col>

                            </Row>
                            <Row gutter={16}>
                                <Col span={16}>
                                    <Item label="备注" name="Remarks">
                                        <TextArea className="input-field" rows={4}/>
                                    </Item>
                                </Col>

                            </Row>
                            <Row gutter={16}>
                                <Col span={16}>
                                    <Item label="条款内容" name="Paymentterms">
                                        <TextArea className="input-field" defaultValue={"Please note:\n" +
                                        "    1.The quotation is based on above mentioned packaging way. \n" +
                                        "    2.Printed stand-up bag is recommended, and relative occuring plate charge is at buyer＇s account. The plate cost depends on bag size and exact design,which should be offered by seller upon receipt of artwork."}
                                                  rows={4}/>
                                    </Item>
                                </Col>
                            </Row>

                        </Collapse.Panel>
                    </Collapse>

                </Form>


            </div>

        );
    }

}

export default QuoteForm;